<?php

declare(strict_types=1);

namespace app\validate\notify;

use think\Validate;

class TemplateValidate extends Validate
{
    protected $rule = [
        'id' => 'require|integer|gt:0',
        'name' => 'require|max:120',
        'title' => 'require|max:255',
        'content' => 'require',
        'type' => 'require|max:80',
        'category' => 'max:60',
        'channels' => 'checkChannels',
        'status' => 'in:0,1',
    ];

    protected $message = [
        'id.require' => '模板ID不能为空',
        'id.integer' => '模板ID必须为整数',
        'id.gt' => '模板ID必须大于0',
        'name.require' => '模板名称不能为空',
        'name.max' => '模板名称不能超过120个字符',
        'title.require' => '模板标题不能为空',
        'title.max' => '模板标题不能超过255个字符',
        'content.require' => '模板内容不能为空',
        'type.require' => '模板类型不能为空',
        'type.max' => '模板类型不能超过80个字符',
        'category.max' => '分类长度不能超过60个字符',
        'status.in' => '状态值不正确',
    ];

    protected $scene = [
        'create' => ['name', 'title', 'content', 'type', 'category', 'channels', 'status'],
        'update' => ['id', 'name', 'title', 'content', 'type', 'category', 'channels', 'status'],
    ];

    protected function sceneCreate(): self
    {
        return $this->only($this->scene['create'])
            ->append('type', 'unique:notify_template,type');
    }

    protected function sceneUpdate(): self
    {
        return $this->only($this->scene['update'])
            ->remove('type', 'unique:notify_template,type')
            ->remove('type', 'require')
            ->remove('name', 'require')
            ->remove('title', 'require')
            ->remove('content', 'require');
    }

    protected function checkChannels($value)
    {
        if ($value === null || $value === '') {
            return true;
        }

        if (is_string($value)) {
            $decoded = json_decode($value, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                return '渠道配置必须是有效的JSON';
            }
            $value = $decoded;
        }

        if (!is_array($value)) {
            return '渠道配置格式必须为数组';
        }

        return true;
    }
}
